package com.athl.netty.netty.codec2;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

/**
 * @author hl
 * @Data 2020/8/31
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建服务器端启动的对象，配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)// 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 设置NioServerSocketChannel作为服务端实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保存活跃状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 给pipeline设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 加入Proto解码器
                            pipeline.addLast("protoDecoder",
                                    new ProtobufDecoder(MyDataPOJO.MyMessage.getDefaultInstance()));
                            pipeline.addLast(new CoderServerHandler());
                        }
                    }); // 设置boosGroup and workerGroup的管道处理器

            System.out.println("服务器准备好了。。。");
            ChannelFuture cf = serverBootstrap.bind(6666).sync();// 启动服务器，绑定端口
            cf.channel().closeFuture().sync(); // 对关闭通道进行监听
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
